package com.zhaoqi.hr.service;

import com.zhaoqi.hr.dto.request.EmployerAuditRequest;
import com.zhaoqi.hr.dto.request.EmployerCreateRequest;
import com.zhaoqi.hr.dto.response.EmployerProfileResponse;
import com.zhaoqi.hr.entity.EmployerProfile;
import com.zhaoqi.hr.entity.EmployerProfile.QualificationStatus;
import com.zhaoqi.hr.entity.User;
import com.zhaoqi.hr.repository.EmployerProfileRepository;
import com.zhaoqi.hr.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用工方档案服务
 */
@Service
public class EmployerProfileService {

    @Autowired
    private EmployerProfileRepository employerProfileRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 获取用工方列表（管理员用）
     */
    @Transactional(readOnly = true)
    public Page<EmployerProfileResponse> getEmployersForAdmin(Pageable pageable, String status) {
        QualificationStatus qualificationStatus = null;
        if (status != null && !status.isEmpty()) {
            try {
                qualificationStatus = QualificationStatus.valueOf(status);
            } catch (IllegalArgumentException e) {
                // 忽略无效的状态值
            }
        }
        
        Page<EmployerProfile> employers = employerProfileRepository.findAllWithUser(qualificationStatus, pageable);
        return employers.map(EmployerProfileResponse::new);
    }

    /**
     * 审核用工方资质
     */
    public void auditEmployer(Long employerId, EmployerAuditRequest request) {
        EmployerProfile profile = employerProfileRepository.findById(employerId)
                .orElseThrow(() -> new RuntimeException("用工方档案不存在"));
        
        profile.setQualificationStatus(QualificationStatus.valueOf(request.getStatus()));
        profile.setQualificationRemark(request.getRemark());
        profile.setUpdatedAt(LocalDateTime.now());
        
        employerProfileRepository.save(profile);
    }

    /**
     * 根据ID获取用工方档案
     */
    @Transactional(readOnly = true)
    public EmployerProfileResponse getEmployerById(Long id) {
        EmployerProfile employer = employerProfileRepository.findByIdWithUser(id)
            .orElseThrow(() -> new RuntimeException("用工方不存在"));
        
        return new EmployerProfileResponse(employer);
    }

    /**
     * 创建用工方（管理员代创建）
     */
    @Transactional
    public EmployerProfileResponse createEmployer(EmployerCreateRequest request) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查手机号是否已存在
        if (userRepository.existsByPhone(request.getPhone())) {
            throw new RuntimeException("手机号已存在");
        }
        
        // 检查身份证号是否已存在
        if (userRepository.existsByIdCard(request.getIdCard())) {
            throw new RuntimeException("身份证号已存在");
        }
        
        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        user.setIdCard(request.getIdCard());
        user.setAddress(request.getAddress());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole(User.UserRole.EMPLOYER);
        user.setStatus(User.UserStatus.APPROVED);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        
        User savedUser = userRepository.save(user);
        
        // 创建用工方档案
        EmployerProfile profile = new EmployerProfile();
        profile.setUser(savedUser);
        profile.setCompanyName(request.getCompanyName());
        profile.setBusinessLicense(request.getBusinessLicense());
        profile.setLegalPerson(request.getLegalPerson());
        profile.setBusinessAddress(request.getBusinessAddress());
        profile.setBusinessScope(request.getBusinessScope());
        profile.setContactPhone(request.getContactPhone());
        profile.setQualificationStatus(QualificationStatus.PENDING);
        profile.setCreatedAt(LocalDateTime.now());
        profile.setUpdatedAt(LocalDateTime.now());
        
        EmployerProfile savedProfile = employerProfileRepository.save(profile);
        
        return new EmployerProfileResponse(savedProfile);
    }
}
